import "./fileupload.scss";
import { UpLoad } from "../svg/svg";
import { ChangeEvent, useState } from "react";
type FileUpLoadProps = Omit<
  React.HTMLAttributes<HTMLInputElement>,
  "children" | "hidden" | "type"
> & {
  // 按钮的文字
  label?: string;
  // 选择完文件后的回调函数
  onFileChange?: (e: any) => void;
  //   是否支持多选文件
  isMultiple?: boolean;
};

export const ImgFileUpLoad = ({
  label,
  onFileChange,
  isMultiple = false,
  ...rest
}: FileUpLoadProps) => {
  const [imgUrl, setImgUrl] = useState<any>();
  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if ((files as FileList).length > 0) {
      const file = files?.[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        setImgUrl(e.target?.result);
      };
      reader.readAsDataURL(file as Blob);
    }
  };

  return (
    <>
      <div className="dashboard_file_up_load_box">
        <div className="dashboard_image_show">
          {imgUrl && <img src={imgUrl} />}
        </div>
        <label
          htmlFor="dashboard_file_up_load"
          className="dashboadr_file_up_load_button"
        >
          <input
            type="file"
            {...rest}
            id="dashboard_file_up_load"
            accept={`image/*`}
            onChange={(e) => handleFileChange(e)}
            multiple={isMultiple}
          />
          <span className="dashboard_file_up_load_label">
            <UpLoad color="#fff" className="dashboard_svg" />
            {label}
          </span>
        </label>
      </div>
    </>
  );
};
